import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { errorResponse, successResponse } from '@/lib/response';
import { UserRole } from '@/constants/user';

async function handler(req: NextRequest) {
    const authResult = await authenticateRequest(req, UserRole.NORMAL_USER);
    if (!authResult.success || !authResult.user) {
        return errorResponse(authResult.error || '身份验证失败');
    }
    const user = authResult.user;

    const { contentId } = await req.json();

    if (!contentId) {
        return errorResponse('Missing contentId');
    }

    await prisma.favorite.delete({
        where: {
            userId_contentId: {
                userId: user.id,
                contentId,
            },
        },
    });

    await prisma.content.update({
        where: { id: contentId },
        data: {
            favoritesCount: {
                decrement: 1,
            },
        },
    });

    return successResponse({ success: true });
}

export const POST = withMiddleware(handler as any);